﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Microsoft.Graph;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using TabbedTemplate.Services;


namespace TabbedTemplate.ViewModels
{
    public class NewIndexPageViewModel : ViewModelBase
    {
        private string _city;

        private static readonly Dictionary<string, Tag> tagDictionary = new()
        {
            ["ChineseFood"] = Tag.ChineseRestuarant,
            ["WesternFood"] = Tag.ForeignRestuarant,
            ["TeaTime"] = Tag.Tea,
            ["CoffeeHouse"] = Tag.Cafe,
            ["DessertTime"] = Tag.CakeAndDesert,
            ["Fastfood"] = Tag.FastRestuarant,
            ["Buffet"] = Tag.Buffet,
            ["Bar"] = Tag.Bar,
            ["OnlyForAdmin"] = Tag.OnlyForAdmin
        };

        public string City
        {
            get => _city;
            set => Set(nameof(City), ref _city, value);
        }

        private string _tagName;

        public string TagName
        {
            get => _tagName;
            set => Set(nameof(TagName), ref _tagName, value);
        }

        /// <summary>
        /// 店铺存储服务
        /// </summary>
        private IStoreService _storeService;

        private ILocationService _locationService;
        private IPunchNavigationService _punchNavigationService;
        private IPreferenceStorage _preferenceStorage;
        private IAlertService _alertService;

        public NewIndexPageViewModel(IStoreService storeService,
            ILocationService locationService,
            IPunchNavigationService punchNavigationService,
            IPreferenceStorage preferenceStorage, IAlertService alertService)
        {
            _locationService = locationService;
            _storeService = storeService;
            _punchNavigationService = punchNavigationService;
            _preferenceStorage = preferenceStorage;
            _alertService = alertService;
        }

        // ******** 绑定命令
        private RelayCommand _pageAppearingCommand;

        private RelayCommand<object> _storeTappedCommand;
        public RelayCommand PageAppearingCommand =>
            _pageAppearingCommand ??= new RelayCommand(async () =>
                await PageAppearingCommandFunction());

        public RelayCommand<object> StoreTappedCommand =>
            _storeTappedCommand ??= new RelayCommand<object>(async tagName =>
                await StoreTappedCommandFunction(tagName));

        public async Task StoreTappedCommandFunction(object tagName)
        {
            TagName = tagName.ToString();
            var tag = tagDictionary[TagName];
            await _punchNavigationService.NavigateToAsync(
                ContentNavigationConstant.IndexPage, tag);
        }

        public async Task PageAppearingCommandFunction()
        {

            try
            {
                var run = false;
                _preferenceStorage.Set("newQuery", true);
                if (!cityLoaded)
                {
                    lock (cityLoadedLock)
                    {
                        if (!cityLoaded)
                        {
                            cityLoaded = true;
                            run = true;
                        }
                    }
                }

                if (!run)
                    return;

                City = _preferenceStorage.Get("City", "北京市");
                _preferenceStorage.Set("Latitude", double.MaxValue);
                _preferenceStorage.Set("Longitude", double.MaxValue);
                _preferenceStorage.Set("City", City);

                var position = await _locationService.GetCurrentLocation();
                if (position != null)
                {
                    _preferenceStorage.Set("isLocationOpened", "true");
                    //为无穷大
                    if (Math.Abs(position.Latitude - double.MaxValue) < 1)
                    {
                        City = "当前GPS信号弱。";
                        await Task.Delay(1000);
                        City = "北京市";
                    }
                    var city = await _locationService.GetCityByPosition(
                            position);
                    //存储当前位置
                    var currentCityBefore =
                        _preferenceStorage.Get("CurrentCity", "");
                    _preferenceStorage.Set("currentLocationLatitude",
                        position.Latitude);
                    _preferenceStorage.Set("currentLocationLongitude",
                        position.Longitude);
                    _preferenceStorage.Set("CurrentCity", city);
                    //如果非第一次，且定位城市未发生变化
                    if (currentCityBefore != "" && currentCityBefore == city)
                    {
                        City = _preferenceStorage.Get("City", "北京市");
                        return;
                    }
                    var res = await _alertService.ShowAlert("提示",
                        "识别到当前城市为 " + city + " 是否切换到当前城市", "确定", "取消");
                    if (res)
                    {
                        City = city;
                        _preferenceStorage.Set("City", city);
                        _preferenceStorage.Set("Latitude", position.Latitude);
                        _preferenceStorage.Set("Longitude", position.Longitude);
                    }

                }
                //如果获取position为null，说明未开启定位
                else
                {
                    cityLoaded = false;
                    _preferenceStorage.Set("isLocationOpened", "false");
                    _alertService.ShowAlert("提示", "当前未开启定位", "确定");
                }
            }
            catch (ServiceException e)
            {
                _alertService.ShowAlert(null, null, null);
            }
        }


        private RelayCommand _searchCommand;

        public RelayCommand SearchCommand =>
            _searchCommand ??= new RelayCommand(async () => await SearchCommandFunction());

        public async Task SearchCommandFunction()
        {
            await _punchNavigationService.NavigationToAsync(
                ContentNavigationConstant.QueryPage);
        }

        private RelayCommand _changeCityCommand;

        public RelayCommand ChangeCityCommand =>
            _changeCityCommand ??= new RelayCommand(async () => await ChangeCityCommandFunction());

        public async Task ChangeCityCommandFunction()
        {
            await _punchNavigationService.NavigationToAsync(
                ContentNavigationConstant.CityLocations);
        }

        /******** 私有变量 ********/

        /// <summary>
        /// 页面已加载。
        /// </summary>
        private volatile bool cityLoaded;

        /// <summary>
        /// 页面已加载锁。
        /// </summary>
        private readonly object cityLoadedLock = new object();
    }
}
